package com.yonyou.iuap.base.sl;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationContext;

public class SpringServiceLocator
{
  private static SpringServiceLocator sl;
  private static ApplicationContext ctx;

  public static SpringServiceLocator getInstance()
    throws Exception
  {
    if (sl == null) {
      sl = new SpringServiceLocator();
      ctx = SpringContextHolder.getApplicationContext();
    }
    return sl;
  }

  public boolean containsBean(String beanKey)
  {
    boolean ret = false;

    if (StringUtils.isEmpty(beanKey)) {
      ret = ctx.containsBean(beanKey);
    }

    return ret;
  }

  public <T> T getService(String beanKey)
    throws Exception
  {
    Object s = null;

    if (StringUtils.isEmpty(beanKey)) {
        throw new Exception("bean id is empty:"+beanKey);
      }
      if (!ctx.containsBean(beanKey)) {
        throw new Exception("spring 中没有找到对应的bean:"+beanKey);
      }

    s = ctx.getBean(beanKey);

    return (T) s;
  }

}